package com.baitengsoft.patentservicemonitor.job.utils;


import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import org.apache.commons.lang.CharSet;
import org.apache.tomcat.util.digester.DocumentProperties;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

/**
 * @author wangze
 * @date 2018-02-08 14:21.
 **/
public class HttpUtils {


    public static String getUrl(Map<String, Object> map) {
        if (map == null || map.size() == 0) {
            return StrUtil.EMPTY;
        }
        StringBuilder builder = new StringBuilder();
        for (String key : map.keySet()) {
            builder.append(String.format("&%s=%s", key, HttpUtil.encode(map.get(key).toString(), CharsetUtil.CHARSET_UTF_8)));
        }
        return '?' + builder.toString().substring(1);
    }


    public static String get(String u, Map<String, Object> map) {
        return HttpUtils.get(u + HttpUtils.getUrl(map));
    }


    public static String get(String u) {
        try {
            URL url = new URL(u);
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            conn.setConnectTimeout(5000);
            String line;
            StringBuilder responseBuilder = new StringBuilder();
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
                while ((line = reader.readLine()) != null) {
                    responseBuilder.append(line);
                }
                reader.close();
                return responseBuilder.toString();
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    public static void main(String[] args) {
        System.out.println(HttpUtils.get("http://www.baidu.com?id=1"));

    }
}
